package com.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
import io.netty.util.ResourceLeakDetector;
import lombok.extern.slf4j.Slf4j;


/**
 * @Author Zhangjy
 * @Date 2021/6/24 15:19
 * @Desc
 */
@Slf4j
public class MyClient {

    public static Channel mychannel = null;

    private static Bootstrap bootstrap = null;

    public static Integer user = null;
    public static String password = null;
    public static String ip = null;
    public static Integer port = null;



    public static void connect() {
        bootstrap= new Bootstrap();
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.option(ChannelOption.SO_BACKLOG, 1024);
            bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel channel) {
//                    channel.pipeline().addLast(new StringEncoder());
                    channel.pipeline().addLast(new StringDecoder());
                    channel.pipeline().addLast(new MyClientHandler());
                }
            });
            ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.ADVANCED);

            mychannel = bootstrap.connect(ip, port).sync().channel();
            sendLoginInfo();
        } catch (Exception e) {
            log.error("tcp connect error：",e );
            System.exit(1);
        }
    }



    public static void reconnect() throws InterruptedException {
        if (!mychannel.isActive()) {
            bootstrap.connect().sync();
            sendLoginInfo();
        }
    }


    public static void sendLoginInfo() {

        if (mychannel.isActive()) {
            ByteBuf buffer = Unpooled.buffer();
            String loginInfo = user + "@" + password + "\r\n";
            buffer.writeCharSequence(loginInfo, CharsetUtil.UTF_8);
            try {
                mychannel.writeAndFlush(buffer).sync();
                if (!mychannel.isActive()) {
                    log.error("登入报文发送错误->{}：", loginInfo);
                }
            } catch (Exception e) {
                log.error("登入报文发送失败1：", e);
            }

        }



    }
}
